import { createApp } from "vue";

const createMyApp = (view, props) => {
    const app = createApp(view, props);
    return app;
};

const insterElement = ({ body, node, brother, insertType }) => {
    let position = "";
    if (insertType == "before") {
        position = "beforebegin";
    } else {
        position = "afterend";
    }
    brother.insertAdjacentElement(position, node);
};

export const renderView = (options) => {
    const { view, body = "body", provide = {}, props = {}, moreNode = false, methods = {}, brother = null, insertType = "after" } = options;

    view.methods = methods;

    const app = createMyApp(view, props);

    for (let key in provide) {
        app.provide(key, provide[key]);
    }
    const div = document.createElement("div");
    const instance = app.mount(div);

    let viewBox = moreNode ? div : div.firstElementChild;
    let parentNode = body;

    if (typeof body == "string") {
        if (!(document.querySelector(body))) {
            console.warn("renderView: selector is null", body);
            return {};
        }
        parentNode = document.querySelector(body);
    }
    if (brother) {
        if (typeof brother == "string" && !(document.querySelector(brother))) {
            console.warn("renderView: brother selector is null", brother);
            return {};
        }
        const brotherNode = typeof brother == "string" ? document.querySelector(brother) : brother;

        insterElement({
            body: parentNode,
            node: viewBox,
            brother: brotherNode,
            insertType,
        });
    } else {
        parentNode.appendChild(viewBox);
    }
    return {
        app,
        instance,
        view: viewBox,
    };
};
export const destroyView = (options) => {
    let { app, view } = options;
    if (app) {
        app.unmount();
        if (view && view.parentNode) {
            view.parentNode.removeChild(view);
        }
        app = null;
        view = null;
    }
};

export default createMyApp;
